<template>
    <my-dailog v-model:show="showFlag" :styleType="20" :showtopclose="true" @close="close">
        <cut-border-box>
            <div class="ljcjbox" v-if="dtData.sellRecordId">
                <div class="dqcjia"> 
                    <p>Current Bid</p>
                    <div class="pmPrice">{{dtData.transactionEthPrice.decimalFourString}}<span>ETH</span></div>
                    <div class="jgmy">≈ ${{dtData.transactionUsdPrice.decimalTwoString}}</div>
                </div>
                
                <div class="zbcj">
                    <stepper v-model="bidAmount" :min='1' :styleType="2"/>
                    <!-- <div class="jiagehs">$ 35.35</div> -->
                    <div class="usdfh">$</div>
                </div>
                <div class="zfhbbox" v-if="settlementCurrency && settlementCurrency.length>0">
                    <van-radio-group v-model="currency">
                        <div class="zfhblist">
                            <template v-for="dt in settlementCurrency" :key="dt">
                                <my-radio :name="dt">{{dt}}</my-radio>
                            </template>
                        </div>
                    </van-radio-group>
                </div>
                <div class="qdcjbtn">
                    <my-button text='Confirm Bid' :styleType="2" @click="goPass"/>
                    <pay-pass v-if="passFlag" @close="passFlag = false" @confirm="confirmBid"/>
                </div>
            </div>
        </cut-border-box>
    </my-dailog>
</template>

<script>
import { reactive,toRefs,getCurrentInstance,computed ,onMounted} from 'vue'
import {useRoute,useRouter} from 'vue-router'
import { useStore } from 'vuex'
import {RadioGroup as vanRadioGroup } from 'vant'
import cutBorderBox from '@/components/cutBorderBox.vue' 
import myDailog from '@/components/myDailog.vue' 
import stepper from '@/components/stepper.vue'
import myButton from '@/components/myButton.vue'
import payPass from '@/components/myButton.vue'
import myRadio from '@/components/myRadio.vue'
import { toast,H5CallAPPFuction } from '@/utils/common'
export default {
    components:{
       cutBorderBox,
       myDailog,
       stepper,
       myButton,
       payPass,
       myRadio,
       vanRadioGroup
    },
    props:{

    },
    setup(props,context){
        const router = useRouter()
        const route = useRoute()
        const store = useStore()
        const {proxy} = getCurrentInstance()

        const state = reactive({
            dtData:computed(()=>store.state.sell.nftdDetail),
            userInfo:computed(()=>store.state.base.userInfo),
            showFlag:true,
            bidAmount:1,
            currency:'',
            passFlag:false,
            settlementCurrency:[],  // 结算货币ETH、USDT、CXT
            ethChain:{eth:0,usdt:0,ethCxt:0}, // eth链钱包余额信息:{"eth":0.00,"usdt":0.00,"ethCxt":0.00}
            assets:{}, // 中心化的cxt资产
        })

        onMounted(()=>{
            if(state.dtData.settlementCurrency){
                state.settlementCurrency = state.dtData.settlementCurrency.split(',')
                state.currency = state.settlementCurrency[0]
            }
            getMYAsset() // 我的资产
            // 定义tradeResults方法，供app调用(app交易处理完成后调用)
            window['tradeResults'] = function (result) { // result：{"success":0,"msg":""}
                if(!result){
                    return toast('No Processing Result') // 没有处理结果
                }
                const rt = JSON.parse(result)
                if(rt.success==0){ // 拍卖出价处理出错了
                    toast(rt.msg)
                }else{
                    toast('Bid Succeeded！')
                    close()
                    state.passFlag = false
                } 
            }

            // App调用，回传ethChain的余额
            window['walletBalance'] = function (objStr) {
                state.ethChain = JSON.parse(objStr)
            }
            try {
                H5CallAPPFuction('jsLoadComplete')  // 调用app的jsLoadComplete方法,通知app，H5页面加载了
                H5CallAPPFuction('getWalletBalance')  // 调用app的getWalletBalance方法,通知app条用H5的walletBalance方法，获取钱包余额，
            } catch (error) {
                console.log("调用app的jsLoadComplete出错了：不是在app环境中调用")
            }
        })

        const getMYAsset=()=>{ // 我的资产
            store.dispatch('capital/get_ctg_income',{
                walletAddress:state.userInfo.walletAddress
            }).then(res=>{
                state.assets = res.data
            })
        }

        const getBidRecord = ()=>{
            return new Promise((resolve,reject) =>{
                store.dispatch('sell/get_auction_bid_record',{
                    limit: 200,
                    orderField: "",
                    orderType: "",
                    page: 1,
                    sellRecordId:state.dtData.sellRecordId // 173 
                }).then(res =>{
                    let bidRecords = []  // 出价记录
                    if(res.data && res.data.length>0){
                        for(let i=0;i<res.data.length;i++){
                            if(res.data[i].bidType==0){ // 只筛选出价记录的数据，（应为接口返回的数据中，包含了上架记录等）
                                bidRecords.push(res.data[i])
                            }
                        }
                    }
                    resolve(bidRecords)
                })
            })
        }

        const goPass = async ()=>{
            const res = await store.dispatch('base/get_exchange_rate',{walletAddress:state.userInfo.walletAddress}) // 获取货币之间的兑换比例
            const rateObj = res.data
            const records = await getBidRecord() // 出价记录
            if(!state.bidAmount){
                return toast('Please Enter The Amount!')
            }else if(records.length==0 && parseFloat(state.bidAmount)<parseFloat(state.dtData.transactionUsdPrice.num)){
                return toast('Must be greater than or equal to the current bid!') // 必须大于等于当前出价
            }else if(records.length>0 && parseFloat(state.bidAmount)<=parseFloat(state.dtData.transactionUsdPrice.num)){
                return toast('Must be greater than the current bid amount!') // 必须大于当前出价
            }
            if(state.currency=='CXT' && parseFloat(state.ethChain.ethCxt)<parseFloat(state.bidAmount) && parseFloat(state.assets.cxtAvailableAmount.num)<parseFloat(state.bidAmount)){
                return toast('CXT balance is insufficient')
            }else if(state.currency=='ETH'){
                // 把美元转化为eth
                const usdToEthAmount = parseFloat(state.bidAmount) * rateObj.exhToCxt
                console.log("美元转化eth：",usdToEthAmount)
                if(parseFloat(state.ethChain.eth)<usdToEthAmount){
                    return toast('ETH balance is insufficient')
                }
                
            }else if(state.currency=='USDT' && parseFloat(state.ethChain.usdt)<parseFloat(state.bidAmount)){
                return toast('USDT balance is insufficient')
            }
           // state.passFlag = true
           //const records = await getBidRecord()
           // 在出竞拍记录里面，判断最后出价的是不是当前用户，不是可以正常出价（同一用户不能连续出价）
            if(records.length>0 && (state.userInfo.walletAddress.toLowerCase() == records[0].bidderAddress.toLowerCase())){
              return toast('Cannot bid consecutively')
            }
            confirmBid()
        }

        const close = ()=>{
            context.emit('close')
        }
        const confirmBid = (pass)=>{
            const appParams = {
                currency:state.currency,
                //chainName:state.dtData.chainName,
                //password:pass,
                bidAmount:state.bidAmount,
                //sellRecordId:state.dtData.sellRecordId,
                bidderAddress:state.userInfo.walletAddress,
                ...state.dtData
            }
            console.log("appParams:",appParams)
            try {
                // 拍卖出价处理: 调用app的auctionBid方法，传入参数交由app处理，H5只接受处理结果（tradeResults方法接收）
                H5CallAPPFuction('auctionBid',JSON.stringify(appParams)) 
            } catch (error) {
                toast('调用app失败')
            }
            // store.dispatch('sell/auction_bid',{
            //     bidAmount:state.bidAmount.toString(),
            //     bidderAddress:state.userInfo.walletAddress,
            //     sellRecordId:state.dtData.sellRecordId
            // }).then(res =>{
            //     if(res.success){
            //         toast('Bid Succeeded！')
            //         state.passFlag = false
            //         close()
            //     }else{
            //         toast(res.message)
            //     }
            // })
            
        }

        return{
            ...toRefs(state),
            close,
            goPass,
            confirmBid
        }
    }
}
</script>

<style lang="scss" scoped>
    .ljcjbox{
        width: 800px;
        height: 500px;
        padding:0 30px 30px 30px;
        font-family: Poppins-Medium, Poppins;
        font-weight: 500;
        font-size: 28px;
        color: #fff;
        line-height: normal;
        .dqcjia{
            display: flex;
            flex-flow: column;
            justify-content: center;
            align-items: center;
            width: 400px;
            margin: 0 auto;
            background: rgba(103,248,255,0.1);
            padding: 20px 30px; 
            p{
                font-size: 30px;
                color: #82A8D4;
            }
            .pmPrice{
                font-size: 38px;
                padding: 5px 0 0 0;
                span{
                    font-size: 24px;
                    padding: 0 0 0 10px;
                }
            }
            .jgmy{
                font-size: 28px;
                color: #67F8FF;
                padding: 10px 0 0 0;
            }        
        }
        .zbcj{
            position: relative;
            padding: 30px 75px 0 75px;
            z-index: 10;
            .usdfh{
                position: absolute;
                z-index: 10;
                left: 190px;
                top: 50px;
                font-family: Poppins-Medium, Poppins;
                font-weight: 500;
                font-size: 28px;
                color: #c1bebe;
            }
            .jiagehs{
                padding: 5px 0 0 0;
                color: #7294CB;
                text-align: center;
            }
        }
        .qdcjbtn{
            width: 300px;
            margin: 30px auto 0 auto;
        }
        .zfhbbox{
            padding: 40px 0 10px 0;
            .zfhblist{
                display: flex;
                justify-content: center;
            }
        }
    }
</style>
<style lang="scss">
    .zfhblist{
        .myRadioBox{
            &+.myRadioBox{
                margin-left: 40px;
            }
        }
    }
</style>